package org.egedede.processmanager.ui;

import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;

import org.egedede.commons.ui.GridBagLayoutBuilder;
import org.egedede.processmanager.ProcessDefinition;
import org.egedede.processmanager.ProcessMode;
import org.egedede.processmanager.ProcessPack;

public class ProcessPackPanel extends JPanel {

	private final ResourceBundle bundle = ResourceBundle.getBundle("ui.ProcessPackPanel");

	private final JList processes = new JList();
	private final JTextField label = new JTextField();
	private final JSpinner mode = new JSpinner();

	public ProcessPackPanel() {
		super(new GridBagLayout());
		this.initGraphics();
	}

	private void initGraphics() {
		final GridBagLayoutBuilder b = new GridBagLayoutBuilder(this, bundle);
		int line = 0;
		b.addXYLabel("label", 0, line);
		b.addXY(label, 1, line);
		line++;

		b.addXYLabel("mode", 0, line);
		b.addXY(mode, 1, line);
		line++;

		b.addXYLabel("Content", 0, line);
		line++;
		b.setWeight(1, 4);
		b.addXYWH(processes, 0, line, 2, 1);

	}

	public void setProcessPack(final ProcessPack pack) {
		label.setText(pack.getLabel());
		mode.setValue(pack.getMode());
		final DefaultListModel<ProcessDefinition> model = (DefaultListModel<ProcessDefinition>) processes.getModel();
		model.removeAllElements();
		for (final ProcessDefinition def : pack.getPack()) {
			model.addElement(def);
		}
	}

	public ProcessPack getProcessPack() {
		final ProcessPack result = new ProcessPack(label.getText(), this.getProcesses(), (ProcessMode) mode.getValue());
		return result;
	}

	private List<ProcessDefinition> getProcesses() {
		final DefaultListModel<ProcessDefinition> model = (DefaultListModel<ProcessDefinition>) processes.getModel();
		final List<ProcessDefinition> result = new ArrayList<ProcessDefinition>();
		for (int i = 0; i < model.getSize(); i++) {
			result.add(model.get(i));
		}
		return result;
	}
}
